using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class CarriageScriptBase : MonoBehaviour, Hittable
{

	float health = 5.0f;
	float distanceToLink;
	float followSpeed = 0.1f;
	public GameObject myLink;

	protected Transform currentEnemy;
	protected Stack<GameObject> myBulletPool;
	protected Pooler poolManager;

	float shootTimer = 0;
	float shootTimerMax = 1.0f;
	bool canShoot = true;
	public float MaxAttackRange = 5.0f ;

	float startedTimer = 0.0f;
	float startedTimerMax = 1.5f;



	void Start()
	{
		poolManager = GameObject.FindGameObjectWithTag ("Pooler").GetComponent<Pooler>();
		myBulletPool = poolManager.basicBulletPool;
		GetEnemies ();
	}


	void Update()
	{
		if(startedTimer < startedTimerMax)
		{
			startedTimer += Time.deltaTime;
		}

		//make my carrage folow me
		Vector3 pullToPos = myLink.transform.position - myLink.transform.forward * 0.5f * distanceToLink;
		transform.LookAt (pullToPos);
		transform.position = Vector3.Lerp (transform.position, pullToPos, followSpeed);
		
		if(!canShoot)
		{
			shootTimer += Time.deltaTime;
			if(shootTimer>shootTimerMax)
			{
				shootTimer = 0.0f;
				canShoot = true;
			}
		}
		
		if(canShoot)
		{
			if(CheckIfEnemyInRange())
			{
				Vector3 enemyDir = (currentEnemy.position - transform.position ).normalized;
				if(!Physics.Linecast(transform.position + enemyDir, currentEnemy.position - enemyDir))
					ShootEnemy(enemyDir);
			}
		}
}
	
	protected virtual void GetEnemies()
	{
	}


	protected virtual bool CheckIfEnemyInRange()
	{
		return false;
	}

	void ShootEnemy(Vector3 dir)
	{

		GameObject bullet = poolManager.GetFromPool (myBulletPool);
		if(bullet)
			bullet.GetComponent<BaseBulletScript>().Shoot(transform.position + dir, Quaternion.LookRotation(dir));
		canShoot = false;

	}

	public void Hit(float damage)
	{
		if (startedTimer > startedTimerMax)
		{
			health -= damage;
			if (health < 0)
			{
				Die();
			}
		}

	}



	public void SetUpCarriage(GameObject link, float distFromLink, float speed)
	{
		myLink = link;
		distanceToLink = distFromLink;
		followSpeed = speed;
	}

	void Die()
	{
		if(myLink != null)
		{
			myLink.GetComponent<TrainLinkerScript>().DestroyLinkAndCarriage();
		}
		else
			Debug.Log ("ERROR: this carriage does not know its linker");
	}
}
